package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.ElementAbstractUrl;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ZheJiangService implements CrawlerScript {


    private static final Logger log = LoggerFactory.getLogger(ZheJiangService.class);
    private static final String province = "浙江";


    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;

    public void start() {
        ChromeDriver driver = chromeBrowser.getChromeDriver();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        try {
            driver.get("http://app.zjepb.gov.cn:8091/zxjc/ddxxAction_getddxxlist");//打开网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            partClickNext(driver, null, jsonObjectList);
            goDetail(driver, jsonObjectList);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            driver.quit();
            log.info("数据爬取结束");
        }
    }

    private void partClickNext(ChromeDriver driver, String html, List<JSONObject> jsonObjectList) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        Elements allElements = parse.getAllElements();
        Elements elementsNew = allElements.select("body > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(1) > td:nth-child(2) > table > tbody:nth-child(2) tr");
        for (Element e : elementsNew) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("企业名称", e.getElementsByTag("td").get(1).text());
            jsonObject.put("区县", e.getElementsByTag("td").get(2).text());
            jsonObject.put("类型", e.getElementsByTag("td").get(3).text());
            jsonObject.put("备注", e.getElementsByTag("td").get(4).text());
            jsonObject.put("详情", ElementAbstractUrl.links(e.getElementsByTag("td").get(5).getElementsByTag("a")));

            jsonObjectList.add(jsonObject);
        }
        try {
            WebElement webElement = driver.findElementByXPath("/html/body/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/table/tbody/tr/td/div[2]/img[3]");
            webElement.click();
        } catch (Exception e) {
            log.error(e.getMessage());
            return;
        }
        log.info("当前页--{}", driver.getCurrentUrl());
        partClickNext(driver, html, jsonObjectList);

    }

    private void goDetail(ChromeDriver driver, List<JSONObject> jsonObjectList) {
        for (JSONObject jsonObject : jsonObjectList) {
            if (!jsonObject.getString("详情").equals("[]")) {
                try {
                    driver.get(jsonObject.getString("详情").substring(1, jsonObject.getString("详情").length() - 1));
                } catch (Exception e) {
                    log.error(e.getMessage());
                    continue;
                }
            } else {
                continue;
            }

            try {
                driver.switchTo().frame("mainFrame");
                driver.switchTo().frame("left");
            } catch (Exception e) {
                log.error(e.getMessage());
                continue;
            }
            try {
                List<WebElement> webElementList = driver.findElements(By.xpath("//*[@id='treeboxbox_tree']/div/table/tbody/tr/td[2]/table/tbody/tr[1]/td[1]/img"));
                for (int j = 0; j < webElementList.size(); j++) {
                    List<MonitorData> monitorDataList = new ArrayList<>();
                    int k = j + 2;
                    try {
                        driver.switchTo().defaultContent();
                        driver.switchTo().frame(driver.findElement(By.id("mainFrame")));
                        driver.switchTo().frame(driver.findElement(By.id("left")));
                        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                        Elements allElements = parse.getAllElements();
                        String CssSelector="#treeboxbox_tree > div > table > tbody > tr:nth-child("+k+")";
                        jsonObject.put("monitor_point",allElements.select(CssSelector).select("table>tbody").get(0).select("tbody>tr").get(0).getElementsByTag("a").text());
                        //driver.findElementsByCssSelector("#treeboxbox_tree > div > table > tbody > tr:nth-child(n+2)");
                        String xpath = "//*[@id='treeboxbox_tree']/div/table/tbody/tr" + "[" + k + "]" + "/td[2]/table/tbody/tr[1]/td[1]/img";
                        driver.findElement(By.xpath(xpath)).click();
                        String xpathStr = "//*[@id='treeboxbox_tree']/div/table/tbody/tr" + "[" + k + "]" + "/td[2]/table/tbody/tr[3]/td[2]/table/tbody/tr/td[4]/span/a";
                        WebElement webElement = driver.findElement(By.xpath(xpathStr));
                        webElement.click();
                        //Thread.sleep(3000);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        continue;
                    }
                    try {
                        partBodyClickNext(driver, jsonObject, null, monitorDataList);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        continue;
                    }
                    saveDataUtil.saveTag(monitorDataList,province);
                }

            } catch (Exception e) {
                log.error("元素点击错误!");
                continue;
            }

        }

    }

    private void partBodyClickNext(ChromeDriver driver, JSONObject jsonObject, String html, List<MonitorData> monitorDataList) {

        try {
            driver.switchTo().parentFrame();
            driver.switchTo().frame(driver.findElement(By.name("ddxx_main")));
        } catch (Exception e) {
            log.error(e.getMessage());
            //return;
        }

        String html1 = driver.getPageSource();
        if (html != null) {
            if (html.equals(html1)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = html1;
        Document parse1 = Jsoup.parse(html1, driver.getCurrentUrl());
        Elements allElements1 = parse1.getAllElements();

        Elements elementstmp = allElements1.select("body > form > table > tbody > tr:nth-child(3) > td > table > tbody > tr:nth-child(1) > td:nth-child(2) > table > tbody:nth-child(2)").get(0).getElementsByTag("tr");
        if (!elementstmp.get(0).text().equals("无实时数据信息")) {
            for (Element e : elementstmp) {
                MonitorData monitorData = new MonitorData();
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setProvince(province);
                monitorData.setCompanyName(jsonObject.getString("企业名称"));
                monitorData.setArea(jsonObject.getString("区县"));
                monitorData.setPollutionType(jsonObject.getString("类型"));
                monitorData.setMonitorPoint(jsonObject.getString("monitor_point"));
                monitorData.setMonitorTime(e.getElementsByTag("td").get(1).text());
                monitorData.setMonitorInfo(e.getElementsByTag("td").get(2).text());
                monitorData.setMonitorValue(e.getElementsByTag("td").get(3).text());
                monitorData.setOverproof(e.getElementsByTag("td").get(4).text());
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);

            }
            try {
                WebElement element = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr/td/div[2]/img[3]"));
                element.click();
                log.info(driver.getCurrentUrl());
                partBodyClickNext(driver, jsonObject, html, monitorDataList);
            } catch (Exception e) {
                log.error("{}--子页面点击下一页超时--{}", driver.getCurrentUrl(), e.getMessage());
                return;
            }
        }
    }
}

